#include <gtk/gtk.h>
#include <glib/poppler.h>
#include <gdk/gdkkeysyms.h>
#include <string.h>
#include <sys/time.h>

#include "vslayout.h"

static GtkWidget* window = NULL;
static PopplerDocument *document = NULL;

#include "vspage.h"

static gchar* get_uri(const gchar *fileName)
{
	gchar *uri;
    gchar *absolute = NULL;
    if ( g_path_is_absolute (fileName) ){
        absolute = g_strdup (fileName);
    } else {
        gchar *current = g_get_current_dir ();
        absolute = g_build_filename (current, fileName, NULL);
        g_free (current);
    }

	uri = g_strdup_printf("file://%s", absolute);
	g_free(absolute);

    return uri;
}

int main(int argc, char *argv[])
{
	gtk_init(&argc, &argv);

	if(argc < 2){
		static char *m_argv[] = {"vspdf", "/home/igor/ch01.pdf"};
		argv = m_argv;
	}

	window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	if(!window){
		puts("window new failed");
		return 1;
	}
	

	gchar* uri = get_uri(argv[1]);
	document = poppler_document_new_from_file(uri, NULL, NULL);
	g_free(uri);
	if(!document){
		puts("document load failed");
		return 1;
	}
	
	VSLayout *vslayout = g_object_new(TYPE_VSLAYOUT, "document", document, NULL);
	if(!vslayout){
		puts("vslayout new failed");
		return 1;
	}

	GtkScrolledWindow *sw = (GtkScrolledWindow*)gtk_scrolled_window_new(NULL, NULL);
	gtk_scrolled_window_set_policy(sw, GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
	gtk_scrolled_window_add_with_viewport(sw, GTK_WIDGET(vslayout));
	gtk_widget_set_usize(GTK_WIDGET(window), 300, 400);

	gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(sw));
	g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit), NULL);
	gtk_widget_show_all(GTK_WIDGET(window));

	gtk_main();

	return 0;
}
